﻿using System;
using System.Web;
using mojoPortal.Business;
using System.Data.Common;
using mojoPortal.Web.Framework;
using mojoPortal.Web.Caching;
using mojoPortal.Web;
using System.Globalization;

namespace blackhouse.Aparts.Web.Handlers {
	public class SiteResolveSoapModule : IHttpModule {
		/// <summary>
		/// You will need to configure this module in the web.config file of your
		/// web and register it with IIS before being able to use it. For more information
		/// see the following link: http://go.microsoft.com/?linkid=8101007
		/// </summary>
		#region IHttpModule Members

		public void Dispose() {
			//clean-up code here.
		}

		public void Init(HttpApplication context) {
			// Below is an example of how you can handle LogRequest event and provide 
			// custom logging implementation for it
			context.PreRequestHandlerExecute += new EventHandler(context_PreRequestHandlerExecute);
		}

		#endregion

		public void context_PreRequestHandlerExecute(object sender, EventArgs e) {
			HttpContext context = HttpContext.Current;
			if (context != null
				&& context.Request.Url.GetLeftPart(UriPartial.Path).Contains(".asmx")
				&& context.Request.UrlReferrer != null) {

				// Dla wywołań bez podzialu na foldery dodatkowe akcje nie są potrzebne
				bool useFolderForSiteDetection = ConfigHelper.GetBoolProperty("UseFoldersInsteadOfHostnamesForMultipleSites", false);
				if (!useFolderForSiteDetection) return;

				string checkUrl = context.Request.UrlReferrer.ToString();
				if (!string.IsNullOrEmpty(checkUrl)) {
					checkUrl = this.GetFolderName(checkUrl);
					context.Items["VirtualFolderName"] = checkUrl;

					string siteFolderName = checkUrl;
					if (siteFolderName.Length == 0) siteFolderName = "root";
					int siteId = SiteSettings.GetSiteIdByFolder(siteFolderName);
					string cachekey = "SiteSettings_" + siteId.ToInvariantString();
					SiteSettings siteSettings = null;
					DateTime expiration = DateTime.Now.AddSeconds(WebConfigSettings.SiteSettingsCacheDurationInSeconds);
					try {
						siteSettings = CacheManager.Cache.Get<SiteSettings>(cachekey, expiration, () =>
						{
							SiteSettings site = new SiteSettings(siteId);
							site.ReloadExpandoProperties();
							site.SiteFolderName = siteFolderName;
							return site;
						});


					}
					catch (Exception) {

					}

					HttpContext.Current.Items["SiteSettings"] = siteSettings;

					if (WebConfigSettings.UseCultureOverride && siteSettings != null) {
						string langCode = ConfigHelper.GetStringProperty("site" + siteSettings.SiteId.ToInvariantString() + "culture", CultureInfo.CurrentCulture.Name);
						if (!string.IsNullOrEmpty(langCode)) {
							CultureInfo ci = new CultureInfo(langCode);
							System.Threading.Thread.CurrentThread.CurrentCulture = ci;
						}
					}

				}
			}
		}

		private string GetFolderName(string requestPath) {

			string folderName = string.Empty;

			requestPath = requestPath.ReplaceEx("https://", string.Empty).ReplaceEx("http://", string.Empty);

			if (requestPath == "/") return folderName;
			if (
				(requestPath.IndexOf("/") > -1)
				&& (requestPath.LastIndexOf("/") > requestPath.IndexOf("/"))
				) {
				requestPath = requestPath.Substring(requestPath.IndexOf("/") + 1, requestPath.Length - requestPath.IndexOf("/") - 1);

				if (requestPath.IndexOf("/") > -1) {
					folderName = requestPath.Substring(0, requestPath.IndexOf("/"));

					try {
						if (!SiteFolder.Exists(folderName)) {
							folderName = string.Empty;
						}
					}
					catch (DbException) {
						folderName = string.Empty;
					}
					catch (InvalidOperationException) {
						// occurs when db tables and procs haven't been created yet
						// in MS SQL
						folderName = string.Empty;
					}
				}
			}

			return folderName;

		}
	}
}
